package com.example.test1.service.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.test1.service.UserService;
import com.example.test1.utils.JwtUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundListOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private JwtUtils jwt;

    @Autowired
    StringRedisTemplate stringRedisTemplate = null;

    /**
     * 微信登录
     * @param code 登录凭证
     * @return openid用户编号、session_key密钥，token令牌
     * @throws Exception
     */

    @Override
    public Map<String, String> logIn(String code) throws Exception {
        String appid = "wxc961d8d896b79e27";
        String secret = "69a85af7af31681b2009fb0438c5dc68";
        String url = "https://api.weixin.qq.com/sns/jscode2session?";
        url += "appid=" + appid + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";

        String res = null;
        //httpClient用于执行HTTP请求并处理响应
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        //httpget用于发送HTTP GET请求
        HttpGet httpget = new HttpGet(url);
        //response用于封装HTTP响应信息
        CloseableHttpResponse response = null;
        //requestConfig用于配置请求相关的参数，依次设置连接超时时间、请求超时时间、响应超时时间和是否允许请求重定向
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(5000)
                .setConnectionRequestTimeout(5000)
                .setSocketTimeout(5000)
                .setRedirectsEnabled(false).build();

        //将之前创建的RequestConfig对象设置为HttpGet请求的配置
        httpget.setConfig(requestConfig);
        //使用execute()方法执行这个GET请求，并获取到服务器返回的响应结果。
        response = httpClient.execute(httpget);
        //获取到了response对象中的实体部分，并将其赋值给responseEntity变量
        HttpEntity responseEntity = response.getEntity();

        if (responseEntity != null) {
            //将HTTP实体转换为字符串，并将结果赋值给变量res
            res = EntityUtils.toString(responseEntity);
            System.out.println(res);
        }

        if (httpClient != null) {
            httpClient.close();
        }

        if (response != null) {
            response.close();
        }

        //将字符串解析为JSON对象
        JSONObject jo = JSON.parseObject(res);
        String openid = jo.getString("openid");
        String session_key = jo.getString("session_key");
        Map<String, String> data = new HashMap<>();
        data.put("openid", openid);
        data.put("session_key", session_key);
        data.put("token", jwt.generateJwtToken(openid, session_key));
        return data;
    }

    /**
     * 写心得
     * @param openId
     * @param content
     * @return
     */

    @Override
    public String writeSecret(String openId, String content) {
        //获取末尾的那个元素
        Set<String> prevContent = stringRedisTemplate.opsForZSet().reverseRange(openId + "Secret", 0, 0);
        //集合为空，说明第一次发布心得
        if (prevContent.size() == 0) {
            stringRedisTemplate.opsForZSet().add(openId + "Secret", content, 1.0);
        }
        //不是第一次，则将新的心得其放在末尾
        else {
            //获取末尾心得的分数
            double score = stringRedisTemplate.opsForZSet().score(openId + "Secret", prevContent.iterator().next());
            stringRedisTemplate.opsForZSet().add(openId + "Secret", content, score + 1.0);
        }
        return "发布成功";
    }

    /**
     * 删除心得
     * @param openId
     * @param content
     * @return
     */

    @Override
    public String deleteSecret(String openId, String content) {
        stringRedisTemplate.opsForZSet().remove(openId + "Secret", content);
        return "删除成功";
    }

    /**
     * 获取所有心得
     * @param openId
     * @return
     */

    @Override
    public Set<String> getSecret(String openId) {
        Set<String> prevContent = stringRedisTemplate.opsForZSet().reverseRange(openId + "Secret", 0, -1);
        return prevContent;
    }
}
